package publicate;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

import protocol.Info;
import wizard.WizardPanelDescriptor;
import client.WelcomePanelDescriptor;

public class PublicateResultsPanelDescriptor extends WizardPanelDescriptor implements ActionListener
{
    public static final String IDENTIFIER = "PUBLICATE_RESULTS_PANEL";
    private PublicateResultsPanel prp;

    public PublicateResultsPanelDescriptor()
    {
        prp = new PublicateResultsPanel();
        prp.addButtonActionListener( this );
        setPanelDescriptorIdentifier( IDENTIFIER );
        setPanelComponent( prp );
    }

    public String getNextPanelDescriptor()
    {
        return null;
    }

    public String getBackPanelDescriptor()
    {
        return WelcomePanelDescriptor.IDENTIFIER;
    }

    public void aboutToDisplayPanel()
    {
        try
        {
            Socket socket = new Socket( Info.HOSTIN, Info.PUBLISH_SERVER );
            System.out.println( "CONNECTED" );
            // zwieksza entropie
            socket.getOutputStream().write( "siedze na koniu\r\n".getBytes() );
            InputStream is = socket.getInputStream();
            BufferedReader in = new BufferedReader( new InputStreamReader( is ) );
            String text = "<br>";
            String s;
            while( !( s = in.readLine() ).equals( "END" ) )
            {
                text += ( s + "<br>" );
                System.out.println( s );
            }
            prp.setInfoText( text );
            socket.close();
        }
        catch( Exception e )
        {
            prp.setInfoText( "There is a problem with connection. Please try again." );
        }
    }

    @Override
    public void actionPerformed( ActionEvent e )
    {
        String hash = prp.getHash();
        try
        {
            Socket socket = new Socket( "localhost", Info.PUBLISH_SERVER );
            socket.getOutputStream().write( ( Info.MSG_CHECK_HASH + hash + "\r\n" ).getBytes() );
            InputStream is = socket.getInputStream();
            BufferedReader in = new BufferedReader( new InputStreamReader( is ) );
            String ans = in.readLine();
            if( ans.equals( "true" ) )
            {
                prp.setHashInfo( "You hash is OK" );
            }
            else
            {
                prp.setHashInfo( "You hash is no okay." );
            }
        }
        catch( Exception ezx )
        {
        }
    }
}
